package cn.rongdao.jrkabao.util;


import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.Uri;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;

import com.github.promeg.pinyinhelper.Pinyin;
import com.mifengkong.frtools.app.FRApplication;
import com.mifengkong.frtools.util.FRCollection;
import com.mifengkong.frtools.util.FRString;
import com.mifengkong.frtools.util.FRToast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.rongdao.jrkabao.BuildConfig;
import cn.rongdao.jrkabao.bean.information.basicinfo.ContactEntity;


/**
 *
 **/
public class CommonUtil {

    public static final String A_LI_PAY_PACKAGE = "com.eg.android.AlipayGphone";
    public static final String WEI_XIN_PAY_PACKAGE = "com.tencent.mm";
    public static final String PIC_FRONT_SUFFIX = "front.jpg";
    public static final String PIC_BACK_SUFFIX = "back.jpg";

    /**
     * 将数组转换为JSON格式的数据。
     *
     * @param contactEntityArrayList 数据源
     * @return JSON格式的数据
     */
    public static String changeArrayDateToJson(ArrayList<ContactEntity> contactEntityArrayList) {
        try {
            JSONArray array = new JSONArray();
            int length = contactEntityArrayList.size();
            for (int i = 0; i < length; i++) {
                ContactEntity contactEntity = contactEntityArrayList.get(i);
                String name = contactEntity.getName();
                String number = contactEntity.getNumber();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("name", name);
                jsonObject.put("tel", number);
                array.put(jsonObject);
            }
            return array.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 如果是前置摄像头的话，将拍出来的图片进行左右翻转
     *
     * @param bmp
     * @return
     */
    public static Bitmap convertBmp(Bitmap bmp) {
        int w = bmp.getWidth();
        int h = bmp.getHeight();

        Matrix matrix = new Matrix();
        matrix.postScale(-1, 1); // 镜像水平翻转

        return Bitmap.createBitmap(bmp, 0, 0, w, h, matrix, true);
    }

    public static String getFormatBankCard(String card) {
        if (FRString.isEmpty(card)) {
            return FRString.EMPTY_STRING;
        }
        StringBuilder sb = new StringBuilder();
        if (card.length() < 4) {
            sb.append("**** **** **** ").append(card);
        } else {
            String afterFour = card.substring(card.length() - 4, card.length());
            sb.append("**** **** **** ").append(afterFour);
        }
        return sb.toString();
    }


    public static String getUUID() {
        UUID uuid = UUID.randomUUID();
        return uuid.toString();
    }

    public static int[] getCurrentYearAndMonth() {
        int[] times = new int[2];
        Calendar calendar = Calendar.getInstance();
        times[0] = calendar.get(Calendar.YEAR);
        times[1] = calendar.get(Calendar.MONTH) + 1;
        return times;
    }

    public static boolean isContainChinese(String str) {
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        return m.find();
    }

    public static String transformPinYin(String character) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < character.length(); i++) {
            sb.append(Pinyin.toPinyin(character.charAt(i)).toUpperCase());
        }
        return sb.toString();
    }

    public static boolean isEnglishAlphabet(String str) {
        Pattern p = Pattern.compile("^[A-Za-z]+$");
        Matcher m = p.matcher(str);
        return m.find();
    }

    /**
     * 判断状态是否为1
     *
     * @param flag
     * @return
     */
    public static boolean isStatusSuccess(int flag) {
        return flag == 1;
    }

    /**
     * 判断状态是否为1
     *
     * @param flag
     * @return
     */
    public static boolean isStatusSuccess(String flag) {
        return !FRString.isEmpty(flag) && flag.equals("1");
    }

    public static String parseMoney(String pattern, BigDecimal bd) {
        DecimalFormat df = new DecimalFormat(pattern);
        return df.format(bd);
    }

    public static String timeStamp2Date(String seconds) {
        if (seconds == null || seconds.isEmpty() || seconds.equals("null")) {
            return "";
        }
        String format = "yyyy-MM-dd HH:mm:ss";
        @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(Long.valueOf(seconds + "000")));
    }

    public static boolean isMobileInstall(String packageName) {
        PackageManager manager = FRApplication.getInstance().getPackageManager();
        List<PackageInfo> pkgList = manager.getInstalledPackages(0);
        for (int i = 0; i < pkgList.size(); i++) {
            PackageInfo pI = pkgList.get(i);
            if (pI.packageName.equalsIgnoreCase(packageName)) {
                return true;
            }
        }
        return false;
    }

    public static void openAppByPackageName(Context context, String packageName) throws PackageManager.NameNotFoundException {
        PackageInfo pi;
        try {
            pi = FRApplication.getInstance().getPackageManager().getPackageInfo(packageName, 0);
            Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
            resolveIntent.setPackage(pi.packageName);
            PackageManager pManager = FRApplication.getInstance().getPackageManager();
            List<ResolveInfo> apps = pManager.queryIntentActivities(resolveIntent, 0);
            ResolveInfo ri = apps.iterator().next();
            if (ri != null) {
                packageName = ri.activityInfo.packageName;
                String className = ri.activityInfo.name;
                Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);//重点是加这个
                ComponentName cn = new ComponentName(packageName, className);
                intent.setComponent(cn);
                context.startActivity(intent);
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Intent getMsgIntent(String phone, String content) {
        Uri smsToUri = Uri.parse(FRCollection.appendAsString("smsto:", phone, ""));
        Intent intent = new Intent(Intent.ACTION_SENDTO, smsToUri);
        intent.putExtra("sms_body", FRString.valueOf(content));
        return intent;
    }

    public static File getSaveFile(Context context, boolean isFront) {
        File file = new File(context.getFilesDir(), isFront ? PIC_FRONT_SUFFIX : PIC_BACK_SUFFIX);
        return file;
    }

    public static File getSaveFile(Context context) {
        File file = new File(context.getFilesDir(), "bank.jpg");
        return file;
    }

    public static String getAppNameByApplicationId() {
        if (isKaMao()) {
            return "卡猫";
        }
        return "卡卡付";
    }

    public static boolean isKaMao() {
        if (BuildConfig.APPLICATION_ID.equals("cn.rongdao.jrkabao")) {
            return true;
        }
        return false;
    }

    public static boolean checkPhone(String phone) {
        if (phone.length() < 11) {
            FRToast.showToastSafe("请输入正确的手机号");
            return false;
        }
        return true;
    }

    public static boolean checkPassword(String p1, String p2) {
        if (!p1.equals(p2)) {
            FRToast.showToastSafe("两次输入的密码不一致，请确认");
            return false;
        }
        return true;
    }

    public static boolean isPasswordCorrect(String... strings) {
        for (String s : strings) {
            if (s.length() < 6) {
                FRToast.showToastSafe("请输入6-20位密码");
                return false;
            }
        }
        return true;
    }

    public static void setCookie(Context context, String url, Set<String> cookieSet) {
        if (cookieSet.size() > 0) {
            Iterator<String> iterator = cookieSet.iterator();
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptCookie(true);
            while (iterator.hasNext()) {
                cookieManager.setCookie(url, iterator.next());
            }
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                cookieManager.flush();
            } else {
                CookieSyncManager.createInstance(context);
                CookieSyncManager.getInstance().sync();
            }
        }
    }
}